<template>
  <div>
    <div style="display:flex; align-items:center; justify-content:space-between; gap:8px; margin-bottom:12px">
      <div style="display:flex; align-items:center; gap:8px">
        <el-input
          v-model="searchQuery"
          placeholder="请输入【医院名称/编码】搜索"
          clearable
          @clear="clearSearch"
          style="width:360px"
        />
      </div>

      <div>
        <el-button type="primary" @click="openAdd" v-if="canAdd">新增医院</el-button>
      </div>
    </div>

    <el-table :data="hospitals" stripe border style="width:100%" remote @sort-change="onSortChange" @header-click="onHeaderClick">
      <el-table-column label="序号" width="80">
        <template #default="{ $index }">{{ (page - 1) * pageSize + $index + 1 }}</template>
      </el-table-column>
      <el-table-column prop="hos_name" label="医院名称" sortable />
      <el-table-column prop="hos_code" label="医院编码" sortable />
      <el-table-column prop="county_name" label="所在区县" sortable />
      <el-table-column prop="remark" label="备注" />
      <el-table-column label="操作" width="140">
        <template #default="{ row }">
          <el-button size="small" @click="openEdit(row)" v-if="canEdit">编辑</el-button>
          <el-button size="small" type="danger" @click="remove(row)" style="margin-left:8px" v-if="canDelete">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin-top:12px; display:flex; justify-content:flex-end; align-items:center">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next"
        :current-page="page"
        :page-size="pageSize"
        :page-sizes="[5,10,20]"
        :total="total"
        @current-change="gotoPage"
        @size-change="onSizeChange"
      />
    </div>

    <el-alert v-if="error" type="error" :title="error" show-icon style="margin-top:12px" />

    <el-dialog :title="editing.id ? '编辑医院' : '新增医院'" v-model="showModal" width="520px">
      <el-form ref="formRef" :model="editing" :rules="rules" label-width="100px">
        <el-form-item prop="hos_name">
          <template #label>医院名称</template>
          <el-input v-model="editing.hos_name" />
        </el-form-item>

        <el-form-item label="医院编码">
          <el-input v-model="editing.hos_code" />
        </el-form-item>

        <el-form-item label="所在区县" prop="county_id">
          <el-select v-model.number="editing.county_id" placeholder="选择区县" filterable clearable>
            <el-option v-for="c in counties" :key="c.id" :label="c.county_name" :value="c.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="备注">
          <el-input v-model="editing.remark" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeModal">取消</el-button>
        <el-button type="primary" @click="submit" :disabled="!canAdd && !canEdit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAuthStore } from '../stores/auth'

const auth = useAuthStore()
const canAdd = computed(() => auth.hasPermission('0105', '新增'))
const canEdit = computed(() => auth.hasPermission('0105', '编辑'))
const canDelete = computed(() => auth.hasPermission('0105', '删除'))

const hospitals = ref<any[]>([])
const counties = ref<any[]>([])
const error = ref('')

// search
const searchQuery = ref('')
const searchTimer = ref<number | null>(null)

// pagination
const page = ref(1)
const pageSize = ref(10)
const total = ref(0)
const totalPages = computed(() => Math.max(1, Math.ceil(total.value / pageSize.value)))

// sorting
const sortBy = ref<string | null>(null)
const sortOrder = ref<'asc' | 'desc' | null>(null)

const showModal = ref(false)
const editing = reactive<any>({ id: null, hos_name: '', hos_code: '', county_id: null, remark: '' })
const formRef = ref<any>(null)

const rules = {
  hos_name: [{ required: true, message: '请输入医院名称', trigger: ['blur', 'change'] }]
}

async function loadCounties() {
  try {
    const res = await auth.apiFetch('/counties')
    counties.value = res.counties || res || []
  } catch (e) {
    counties.value = [{ id: 1, county_name: '示例区县A' }, { id: 2, county_name: '示例区县B' }]
  }
}

async function load() {
  error.value = ''
  await loadCounties()
  try {
    // if search or sorting requested, fetch all and filter locally for reliable behavior
    if (sortBy.value || (searchQuery.value && String(searchQuery.value).trim() !== '')) {
      const params = new URLSearchParams()
      params.set('limit', '1000000')
      const res = await auth.apiFetch(`/hospitals?${params.toString()}`)
      const all = (res.hospitals || res || []).map((h: any) => ({ ...h }))

      const q = String(searchQuery.value || '').trim().toLowerCase()
      let filtered = all
      if (q) {
        filtered = all.filter((h: any) => {
          const name = String(h.hos_name || '').toLowerCase()
          const code = String(h.hos_code || '').toLowerCase()
          const county = String(h.county_name || '').toLowerCase()
          return name.includes(q) || code.includes(q) || county.includes(q)
        })
      }

      const prop = sortBy.value
      const order = sortOrder.value === 'asc' ? 1 : -1
      if (prop) {
        filtered.sort((a: any, b: any) => {
          const va = a[prop] ?? ''
          const vb = b[prop] ?? ''
          if (typeof va === 'number' && typeof vb === 'number') return (va - vb) * order
          const sa = String(va).toLowerCase()
          const sb = String(vb).toLowerCase()
          if (sa < sb) return -1 * order
          if (sa > sb) return 1 * order
          return 0
        })
      }

      total.value = filtered.length
      hospitals.value = filtered.slice((page.value - 1) * pageSize.value, page.value * pageSize.value)
    } else {
      const params = new URLSearchParams()
      params.set('page', String(page.value))
      params.set('limit', String(pageSize.value))
      if (sortBy.value) params.set('sort_by', sortBy.value)
      if (sortOrder.value) params.set('sort_order', sortOrder.value)

      const res = await auth.apiFetch(`/hospitals?${params.toString()}`)
      hospitals.value = (res.hospitals || res || []).map((h: any) => ({ ...h }))
      total.value = typeof res.total === 'number' ? res.total : hospitals.value.length
    }
  } catch (e) {
    hospitals.value = []
    total.value = 0
    error.value = '加载医院数据失败'
  }
}

onMounted(async () => {
  await loadCounties()
  await load()
})

async function openAdd() {
  if (!canAdd.value) { ElMessage.warning('没有新增权限'); return }
  await loadCounties()
  editing.id = null
  editing.hos_name = ''
  editing.hos_code = ''
  editing.county_id = null
  editing.remark = ''
  showModal.value = true
}

async function openEdit(h: any) {
  if (!canEdit.value) { ElMessage.warning('没有编辑权限'); return }
  await loadCounties()
  editing.id = h.id
  editing.hos_name = h.hos_name || ''
  editing.hos_code = h.hos_code || ''
  editing.county_id = h.county_id ?? null
  editing.remark = h.remark || ''
  showModal.value = true
}

function closeModal() { showModal.value = false }

async function submit() {
  error.value = ''
  try {
    if (formRef.value) {
      await formRef.value.validate()
    } else {
      if (!editing.hos_name) { error.value = '请填写医院名称'; ElMessage.error(error.value); return }
    }

    if (editing.id && !canEdit.value) { ElMessage.error('没有编辑权限'); return }
    if (!editing.id && !canAdd.value) { ElMessage.error('没有新增权限'); return }

    if (editing.id) {
      const payload: any = { hos_name: editing.hos_name, hos_code: editing.hos_code, county_id: editing.county_id, remark: editing.remark }
      await auth.apiFetch(`/hospitals/${editing.id}`, { method: 'PUT', body: JSON.stringify(payload) })
      ElMessage.success('编辑成功')
    } else {
      const payload = { hos_name: editing.hos_name, hos_code: editing.hos_code, county_id: editing.county_id, remark: editing.remark }
      await auth.apiFetch('/hospitals', { method: 'POST', body: JSON.stringify(payload) })
      ElMessage.success('新增成功')
    }
    closeModal()
    await load()
  } catch (e: any) {
    try { const body = await e.json(); error.value = body.message || '操作失败' } catch { error.value = '操作失败' }
    ElMessage.error(error.value)
  }
}

async function remove(h: any) {
  error.value = ''
  if (!canDelete.value) { ElMessage.warning('没有删除权限'); return }
  ElMessageBox.confirm(`确定删除医院 ${h.hos_name || ''} ?`, '删除确认', {
    confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
  }).then(async () => {
    try {
      await auth.apiFetch(`/hospitals/${h.id}`, { method: 'DELETE' })
      ElMessage.success('删除成功')
      if (hospitals.value.length === 1 && page.value > 1) page.value = page.value - 1
      await load()
    } catch (e: any) {
      try { const body = await e.json(); error.value = body.message || '删除失败' } catch { error.value = '删除失败' }
      ElMessage.error(error.value)
    }
  }).catch(() => {})
}

function gotoPage(n: number) {
  if (n < 1) n = 1
  if (n > totalPages.value) n = totalPages.value
  page.value = n
  load()
}

function onSizeChange(size: number) {
  pageSize.value = size
  gotoPage(1)
}

function onSortChange(sort: any) {
  const column = sort && sort.column ? sort.column : null
  const prop = sort && sort.prop ? sort.prop : (column ? (column.property ?? column.prop ?? null) : null)
  const orderRaw = sort && sort.order ? sort.order : null

  let order: string | null = null
  if (orderRaw) {
    order = (orderRaw === 'ascending' || orderRaw === 'asc') ? 'asc' : 'desc'
  } else if (prop && prop === sortBy.value) {
    if (sortOrder.value === 'asc') order = 'desc'
    else if (sortOrder.value === 'desc') order = null
    else order = 'asc'
  }

  if (!prop || !order) { sortBy.value = null; sortOrder.value = null }
  else { sortBy.value = String(prop); sortOrder.value = order as 'asc' | 'desc' }

  page.value = 1
  load()
}

function onHeaderClick(column: any) {
  if (!column) return
  const prop = column.property ?? column.prop ?? null
  if (!prop) return
  if (!column.sortable && column.sortable !== 'custom' && column.sortable !== true) return

  if (sortBy.value !== prop) { sortBy.value = String(prop); sortOrder.value = 'asc' }
  else { if (sortOrder.value === 'asc') sortOrder.value = 'desc'; else if (sortOrder.value === 'desc') { sortBy.value = null; sortOrder.value = null } else sortOrder.value = 'asc' }

  page.value = 1
  load()
}

function clearSearch() { searchQuery.value = ''; page.value = 1; load() }

watch(searchQuery, () => {
  if (searchTimer.value) clearTimeout(searchTimer.value)
  searchTimer.value = window.setTimeout(() => { page.value = 1; load() }, 350)
})
</script>

<style scoped>
</style>
